<template>
  <a-drawer v-model:open="drawerOpen" width="800" title="PDF预览">
      <div class="pdf-container">
          <div class="pdf-wrapper-box" v-for="(page, index) in pages" :key="index">
            <div :ref="(el) => add(el as HTMLElement)" class="pdf-wrapper" :style="{ width: PDF_WIDTH + 'px', height: PDF_HEIGHT + 'px' }">
                <div v-if="index === 0" style="padding: 16px;">
                  <h2 style="text-align: center;">PDF图片</h2>
                </div>
                <a-table bordered :pagination="false" :columns="columns" :data-source="page"></a-table>
                <div style="position: absolute;bottom: 20px;text-align: center;left: 0;right: 0;">第{{index + 1}}页</div>
            </div>
          </div>
      </div>
      <template #footer>
        <div style="text-align: center;">
          <a-button style="margin-right: 20px;">取消</a-button>
          <a-button type="primary" @click="create">生成PDF</a-button>
        </div>
      </template>
    </a-drawer>
</template>
<script setup lang="ts">
import { createImageToPDF } from '@/utils/pdf';
import { ref, defineExpose, computed } from 'vue';

const PDF_WIDTH = 595.28
const PDF_HEIGHT = 841.89

const drawerOpen = ref(false)
const pdfPages = ref<HTMLElement[]>([])
const tableData = ref<any[]>([])

const pages = computed(() => {
  let pageNo = 1
  const pageSize = 10
  const arr = [] as any[][]
  while(tableData.value[(pageNo - 1) * pageSize]) {
    arr.push(tableData.value.slice((pageNo - 1) * pageSize, pageNo * pageSize))
    pageNo++
  }
  return arr
})

const columns = [
  {
    title: 'Age',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: 'Age',
    dataIndex: 'age',
    key: 'age',
  },
  {
    title: 'Address',
    dataIndex: 'address',
    key: 'address',
  },
];

for (let index = 0; index < 60; index++) {
  tableData.value.push({
    name: 'Edward King 1',
    age: 32,
    address: 'London, Park Lane no. 1',
  })
}

function add(el: HTMLElement) {
  if(!pdfPages.value.find(item => item === el)) {
    pdfPages.value.push(el)
  }
}

function create() {
  createImageToPDF(pdfPages.value)
}

defineExpose({
  open() {
    pdfPages.value = []
    drawerOpen.value = true
  }
})
</script>

<style scoped>
.pdf-container {
  background: rgba(0, 0, 0, 0.05);
  display: flex;
  padding: 20px;
  box-sizing: border-box;
  height: 100%;
  overflow: auto;
  flex-direction: column;
  align-items: center;
}

.pdf-wrapper-box {
  display: flex;
  justify-content: center;
  margin-bottom: 16px;
  width: 100%;
}

.pdf-wrapper {
  background: #fff;
  box-sizing: border-box;
  padding: 40px 40px;
  position: relative;
}
</style>